﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;


namespace YTSK.Vouch
{
    public class VouchToolBar : VouchCount
    {
        public int _id;
        public string _ts;
        public bool _bVouchModifyStatus;
        private ToolStrip _toolstrip;
        private string _cdefine2;

        #region 初始化
        public VouchToolBar(string cvouchtype, Control c, ToolStrip toolstrip, string cdefine2) :
            base(cvouchtype, c)
        {
            base._bControlHandle = false;
            _cdefine2 = cdefine2;
            _toolstrip = toolstrip;
        }
        #endregion

        #region 初始化
        public override void Init()
        {
            base.Init();
            SetToolBarEnable(true);
        }
        #endregion


        #region 下载金立或者九机单据
        /// <summary>
        /// 下载金立或者九机单据
        /// </summary>
        /// <param name="stype"></param>
        public void DownloadData(string stype,string retailcode)
        {

            var oldURL = "";
            var err = "";
            switch (stype)
            {
                case "待开票":
                    var f = new Frm.FrmVouchDKP();
                    f.ShowDialog();
                    retailcode = f.report._retailcode;
                    f.Close();
                    if (retailcode.ObjToString().Length == 0)
                    {
                        err = "没有输入单号";
                        var ferr = new FrmMessage();
                        ferr.ShowMsg(false, "提示", err);
                        return;
                    }
                    oldURL = "{0}/api/oms/YT_DownLoadFromERP/DownLoadFromERPLS?token={1}&retailcode={2}";
                    break;
                case "金立零售":
                    oldURL = "{0}/api/oms/YTSH_DownLoadJL/DownLoadFromERPLS?token={1}&retailcode={2}&IDWarehouse={3}";
                    break;
                case "九机零售":
                    oldURL = "{0}/api/oms/YT_9JDownload/DownLoadFromERPLS?token={1}&retailcode={2}&IDWarehouse={3}";
                    break;
                case "金立分销":
                    oldURL = "{0}/api/oms/YTSH_DownLoadJL/DownLoadFromERPFX?token={1}&retailcode={2}&IDWarehouse={3}";
                    break;
                case "九机分销":
                    oldURL = "{0}/api/oms/YT_9JDownload/DownLoadFromERPFXSH?token={1}&retailcode={2}&IDWarehouse={3}";
                    break;
                case "3C分销":
                default:
                    oldURL = "{0}/api/oms/YTSH_3C/DownLoadFrom3C?token={1}&retailcode={2}&IDWarehouse={3}";
                    break;
            }

            #region 弹出选择金立分销
            if (retailcode.Length == 0)
            {
                var f = new FrmKP.FrmVouchCode();
                f.Text = "单据引入" + stype;
                f.ShowDialog();
                retailcode = f.cCode;
                _idwarehouse = f.idwarehouse;
            }
            if (retailcode.ObjToString().Length == 0)
            {
                err = string.Format("单据号[{0}]没有输入；", retailcode);
                var ferr = new FrmMessage();
                ferr.ShowMsg(false, "提示", err);
                return;
            }
            #endregion

            #region 获取销售小票
            var url = string.Format(oldURL, ServerConfig.ServerAddress, ServerConfig.GetToken(), retailcode, _idwarehouse);
            var s = Common.handleHttp.Get(url);
            var result = Common.handleJSON.DeserializeResult(s);
            if (result.result != 1)
            {
                err = string.Format("下载单据失败-{0}", result.resultdetail);
                var ferr = new FrmMessage();
                ferr.ShowMsg(false, "提示", err);
                return;
            }
            var m_v = (Dictionary<string, object>)result.GetVal("rdrecord");
            if(ServerConfig._company== Company.上海Iteng)
            {
                if (m_v.ContainsKey("cDf10"))
                { m_v["cDf10"] = m_v["cMemo"]; }
            }
            var l_rds = result.GetListDic("rdrecords");
            #endregion


            if (this._bVouchModifyStatus == false)
            {
                this.DisplayDataForm(m_v); this.Displaydata(l_rds, true);
                this._id = 0; this._ts = "";
                this.SetDefaultWarehouse();
            }
            else
            {
                this.Displaydata(l_rds, false);
            }
            this.SetToolBarEnable(false);
            this._bVouchModifyStatus = true;

        }
        #endregion



        #region 删除当前行
        public void DelRow()
        {
            var row = base._dg.CurrentRow;
            if (row == null) { return; }
            var o = row.Index;
            if (o >= 0)
            {
                if (ServerConfig._company == Company.上海Iteng)
                {
                    if (row.Cells["cInvCode"].Value.ObjToString().Length > 0)
                    {
                        var isumsale = row.Cells["iSumSale"].Value.ObjToDecimal();
                        if (isumsale > 0 & isumsale < 100)
                        {
                            MessageBox.Show("已经对照的存货，不允许删行");
                            return;
                        }
                    }
                }
                base._dg.Rows.RemoveAt(o);

            }
            base.sumcolAll();
        }
        #endregion


        #region 获取单据上的数据-返回主表数据
        /// <summary>
        /// 获取单据上的数据-返回主表数据
        /// </summary>
        /// <param name="err"></param>
        /// <param name="l_detail">明细表数据</param>
        /// <returns></returns>
        public Dictionary<string, object> GetVouchData(out string err, out List<Dictionary<string, object>> l_detail)
        {
            err = "";
            var dicmain = new Dictionary<string, object>();
            l_detail = new List<Dictionary<string, object>>();
            var vmain = base._vouchs.Where(x => x.iHead == 1).ToList();
            for (int i = 0; i < vmain.Count; i++)
            {
                var vou = vmain[i];
                var call = base._main.Controls.Find(vou.FieldCode, true);
                string val = null;
                if (call.Count() > 0)
                {
                    var c0 = call[0];
                    switch (vou.ControlType)
                    {
                        case "input":
                            var tb = (TextBox)c0;
                            if (tb.Text.Trim().Length > 0) { val = tb.Text.Trim(); }
                            break;
                        case "select":
                            var cb = (ComboBox)c0;
                            var tmp = (DataRowView)cb.SelectedItem;
                            string v;
                            if (tmp != null)
                            { v = tmp["key"].ObjToString(); }
                            else { v = cb.Text; }
                            val = v;
                            break;
                        case "date":
                            var dt = (DateTimePicker)c0;
                            val = dt.Value.ToString("yyyy-MM-dd");
                            break;
                    }
                }
                if (vou.bNeed == true)
                {
                    if (val.ObjToString().Length == 0)
                    {
                        err += string.Format("请录入[{0}]", vou.FieldTitle);
                    }
                }
                if (val != null)
                {
                    dicmain.Add(vou.FieldCode, val);
                }
            }
            #region 结算方式必须输入
            if (dicmain.Keys.Contains("cSettleStyle"))
            {
                if (dicmain["cSettleStyle"].ObjToString() == "") { err += "请录入收款方式"; }
            }
            #endregion

            var vdetail = base._vouchs.Where(x => x.iHead == 2 && x.FieldCode != "dataGrid").ToList();
            for (int i = 0; i < base._dg.Rows.Count; i++)
            {
                var dgr = base._dg.Rows[i];
                var dic = new Dictionary<string, object>();
                for (int j = 0; j < base._dg.Columns.Count; j++)
                {
                    var col = base._dg.Columns[j];
                    dic.Add(col.Name, dgr.Cells[j].Value);
                }
                l_detail.Add(dic);
            }
            dicmain.Add("ID", _id);
            dicmain.Add("ts", _ts);
            return dicmain;
        }

        #endregion 

        #region 取消保存，把单据清空
        /// <summary>
        ///  取消保存，把单据清空
        /// </summary>
        public void Cancel_Rd()
        {
            try
            {
                if (_id == 0)
                {
                    var rd = new Dictionary<string, object>();
                    _id = 0;
                    _ts = "";
                    var rds = new List<Dictionary<string, object>>();
                    base.DisplayDataForm(rd);
                    base.Displaydata(rds, true);
                    SetToolBarEnable(true);
                    _bVouchModifyStatus = false;
                }
                else { Reflesh_Rd(_id); }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion




        #region 刷新

        public void Reflesh_Rd(int id)
        {
            try
            {
                _id = id;
                var url = string.Format("{0}/api/oms/Rdrecord11/GetOne?token={1}&id={2}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken(), _id);
                var s = Common.handleHttp.Get(url);
                var result = Common.handleJSON.DeserializeResult(s);
                if (result.result != 1) { MessageBox.Show("出错:" + result.resultdetail); return; }

                #region 显示数据
                var rd = (Dictionary<string, object>)result.GetVal("rdrecord");
                _id = rd["ID"].ObjToInt();
                _ts = rd["ts"].ObjToString();
                var rds = result.GetListDic("rdrecords");
                base.DisplayDataForm(rd);
                base.Displaydata(rds, true);
                SetToolBarEnable(true);
                _bVouchModifyStatus = false;
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion

        #region 设置工具栏
        public virtual void SetToolBarEnable(bool bEnable)
        {
            var enablestr = new List<string>() { "修改", "上一张", "下一张", "弃审", "审核", "税控开票", "打印发票", "退出" };
            var disablestr = new List<string>() { "待开客户", "拆行", "删行", "保存", "放弃" };
            foreach (ToolStripItem bar in _toolstrip.Items)
            {
                var text = bar.Text;
                if (enablestr.Contains(text)) { bar.Enabled = bEnable; }
                if (disablestr.Contains(text)) { bar.Enabled = !bEnable; }
            }
            base._dg.ReadOnly = bEnable;
            var vou = base._vouchs.Where(x => x.iHead == 1 && x.bModify != 0).ToList();
            for (int i = 0; i < vou.Count; i++)
            {
                var v = vou[i];
                var c = base._main.Controls.Find(v.FieldCode, true);
                if (c.Count() > 0)
                {
                    var c0 = c[0];
                    switch (v.ControlType)
                    {
                        case "input":
                            var tb = (TextBox)c0;
                            tb.ReadOnly = bEnable;
                            break;
                        case "date":
                            var dt = (DateTimePicker)c0;
                            dt.Enabled = !bEnable;
                            break;
                        case "select":
                            var cb = (ComboBox)c0;
                            cb.Enabled = !bEnable;
                            break;
                    }
                }
            }
            base.bControlHandle = !bEnable;
        }

        #endregion


        #region 拆行

        public virtual void Spin()
        {
            try
            {
                #region 检查
                var row = base._dg.CurrentRow;
                var colunmname = "";
                if (colunmname == "")
                {
                    if (_dg.Columns.Contains("iQuantity"))
                    { colunmname = "iQuantity"; }
                }
                if (_dg.Columns.Contains("cDefine31"))
                {
                    colunmname = "cDefine31";
                }
                if (colunmname == "") { MessageBox.Show("找不到数量列"); return; }
                var itatol = row.Cells[colunmname].Value.ObjToDecimal();
                if (itatol == 0) { MessageBox.Show("数量为0"); return; }
                #endregion
                #region 提示
                var f = new Frm.FrmSpin();
                f.Init(itatol);
                f.ShowDialog();
                var ispin = f.GetSpin();
                if (ispin == 0) { return; }
                _dg.Rows.InsertCopy(row.Index, row.Index + 1);
                var rownew = _dg.Rows[row.Index + 1];
                for (int j = 0; j < _dg.Columns.Count; j++)
                {
                    rownew.Cells[j].Value = row.Cells[j].Value;
                }
                if (_dg.Columns.Contains("AutoID"))
                {
                    rownew.Cells["AutoID"].Value = 0;
                }
                if (_dg.Columns.Contains("cDefine31"))
                {
                    row.Cells["cDefine31"].Value = itatol - ispin;
                    rownew.Cells["cDefine31"].Value = ispin;
                    if (_dg.Columns.Contains("cDefine32") && _dg.Columns.Contains("cDefine33"))
                    {
                        var dj = row.Cells["cDefine32"].Value.ObjToDecimal();
                        row.Cells["cDefine33"].Value = Math.Round((itatol - ispin) * dj, 2, MidpointRounding.AwayFromZero);
                        rownew.Cells["cDefine33"].Value = Math.Round(ispin * dj, 2, MidpointRounding.AwayFromZero);
                    }
                }
                if (_dg.Columns.Contains("iQuantity"))
                {
                    row.Cells["iQuantity"].Value = itatol - ispin;
                    rownew.Cells["iQuantity"].Value = ispin;
                    if (_dg.Columns.Contains("iUnitPriceSale") &&
                        _dg.Columns.Contains("iMoneySale") && _dg.Columns.Contains("iTaxSale")
                        && _dg.Columns.Contains("iSumSale") && _dg.Columns.Contains("iTaxRateSale"))
                    {
                        var dj = row.Cells["iUnitPriceSale"].Value.ObjToDecimal();
                        var itaxrate = row.Cells["iTaxRateSale"].Value.ObjToDecimal();
                        var isum = Math.Round((itatol - ispin) * dj, 2, MidpointRounding.AwayFromZero);
                        var imoney = Math.Round(isum / (1 + itaxrate / 100), 2, MidpointRounding.AwayFromZero);
                        var itax = isum - imoney;
                        row.Cells["iSumSale"].Value = isum;
                        row.Cells["iMoneySale"].Value = imoney;
                        row.Cells["iTaxSale"].Value = itax;
                        isum = Math.Round(ispin * dj, 2, MidpointRounding.AwayFromZero);
                        imoney = Math.Round(isum / (1 + itaxrate / 100), 2, MidpointRounding.AwayFromZero);
                        itax = isum - imoney;
                        rownew.Cells["iSumSale"].Value = isum;
                        rownew.Cells["iMoneySale"].Value = imoney;
                        rownew.Cells["iTaxSale"].Value = itax;
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion


        #region 税控开票-开票申请
        /// <summary>
        /// 税控开票-开票申请
        /// </summary>
        public void VouchToFP_Rd(Form parent)
        {
            var err = "";
            var url = string.Format("{0}/api/oms/Rd2SK/GetOneForKPTry?token={1}&id={2}",
                ServerConfig.ServerAddress, ServerConfig.GetToken(), this._id);
            var resultval = Common.handleHttp.Get(url);
            var result = Common.handleJSON.DeserializeResult(resultval);
            if (result.result != 1)
            {
                err = result.resultdetail;
                var ferr = new FrmMessage();
                ferr.ShowMsg(false, "开票出错", err);
                return;
            }
            var b_dzfp = result.value["bYKP"].ObjToBool();
            #region 电子发票开具
            if (b_dzfp == true)
            {
                var bret = VouchToFP_RD_Proc(this._id);
                if (!bret) { return; }
                var ftip = new FrmTip();
                ftip.Show();
                var isecond = 0;
                while (isecond < 20)
                {
                    ftip.setValue("发票开票请求已经发送，正在等待开票结果，请稍侯...", isecond);
                    System.Threading.Thread.Sleep(500);
                    isecond++;
                }
                ftip.Close();
                VouchToFP_RD_Proc_Status(this._id,false);
            }
            #endregion
            else
            {
                cSK.cDll.SetCursorPos(1,1);
                url = string.Format("{0}/api/oms/Rd2SK/GetOneForKP?token={1}&id={2}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken(), this._id);
                resultval = Common.handleHttp.Get(url);
                result = Common.handleJSON.DeserializeResult(resultval);
                if (result.result != 1)
                {
                    err = result.resultdetail;
                    var ferr = new FrmMessage();
                    ferr.ShowMsg(false, "获取开票信息有错", err);
                    return;
                }
                var t = (Dictionary<string, object>)result.GetVal("main");
                var sk = t.ToObj<Model.SK_SalebillVouch>();
                var l_sks = result.GetList<Model.SK_SalebillVouchs_View>("details");

                err = cSK.SoftSel.proc(sk, l_sks);
                if (err.Length > 0) { MessageBox.Show(err); }
            }
        }

        public static bool VouchToFP_RD_Proc(int id)
        {
            var err = "";
            var url = string.Format("{0}/api/oms/Rd2SK/SetWeb_RD?token={1}&id={2}",
                ServerConfig.ServerAddress, ServerConfig.GetToken(), id);
            var resultval = Common.handleHttp.Get(url);
            var result = Common.handleJSON.DeserializeResult(resultval);
            if (result.result != 1)
            {
                err = System.Web.HttpUtility.UrlDecode(result.resultdetail);
                var ferr = new FrmMessage();
                ferr.ShowMsg(false, "电子发票开具有错", err);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 税控开票-开票申请
        /// </summary>
        public void VouchToFP_SK(Form parent)
        {
            var err = "";
            List<Dictionary<string, object>> l_detail_dic;
            var main_dic = GetVouchData(out err, out l_detail_dic);
            var main = main_dic.ToObj<Model.SK_SalebillVouch>();
            var l_detail = l_detail_dic.ToList<Model.SK_SalebillVouchs_View>();
            if (err.Length > 0) 
            {
                var ferr = new FrmMessage();
                ferr.ShowMsg(false, "获取开票数据有错", err);
                return;
            }
            var url = string.Format("{0}/api/oms/Rd2SK/GetOneForKPTry?token={1}&id={2}",
                ServerConfig.ServerAddress, ServerConfig.GetToken(), this._id);
            var resultval = Common.handleHttp.Get(url);
            var result = Common.handleJSON.DeserializeResult(resultval);
            if (result.result != 1)
            {
                err = result.resultdetail;
                var ferr = new FrmMessage();
                ferr.ShowMsg(false, "开票出错", err);
                return;
            }
            var b_dzfp = result.value["bYKP"].ObjToBool();
            #region 电子发票开具
            if (b_dzfp == true)
            {
                var bret = VouchToFP_SK_Proc(ref main,l_detail);
                if (!bret) { return; }
                var ftip = new FrmTip();
                ftip.Show();
                var isecond = 0;
                while (isecond < 20)
                {
                    ftip.setValue("电子发票开票请求已经发送，正在等待开票结果，请稍侯...", isecond);
                    System.Threading.Thread.Sleep(500);
                    isecond++;
                }
                ftip.Close();
                bret=VouchStatus_SK_Proc(main.ID,out err);
                var frm = new FrmMessage();
                frm.ShowMsg(bret, "提醒", err);
            }
            #endregion
            else
            {
                url = string.Format("{0}/api/oms/Rd2SK/GetOneForKP_Part?token={1}&id={2}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken(), this._id);
                var dic = new Dictionary<string, object>();
                dic.Add("main", main);
                dic.Add("detail", l_detail);
                resultval = Common.handleHttp.Post(dic, url);
                result = Common.handleJSON.DeserializeResult(resultval);
                if (result.result != 1)
                {
                    err = result.resultdetail;
                    var ferr = new FrmMessage();
                    ferr.ShowMsg(false, "获取开票信息有错", err);
                    return;
                }
                var t = (Dictionary<string, object>)result.GetVal("main");
                var sk = t.ToObj<Model.SK_SalebillVouch>();
                var l_sks = result.GetList<Model.SK_SalebillVouchs_View>("details");

                err = cSK.SoftSel.proc(sk, l_sks);
                if (err.Length > 0) { MessageBox.Show(err); }
            }
        }

        public static bool VouchToFP_SK_Proc(ref Model.SK_SalebillVouch main,List<Model.SK_SalebillVouchs_View> l_detail)
        {
            var err = "";
            var url = string.Format("{0}/api/oms/Rd2SK/SetWeb_SK?token={1}",
                ServerConfig.ServerAddress, ServerConfig.GetToken());
            var dic = new Dictionary<string, object>();
            dic.Add("main", main);
            dic.Add("detail", l_detail);
            var resultval = Common.handleHttp.Post(dic,url);
            var result = Common.handleJSON.DeserializeResult(resultval);
            if (result.result != 1)
            {
                err = result.resultdetail;
                var ferr = new FrmMessage();
                ferr.ShowMsg(false, "电子发票开具有错", err);
                return false;
            }
            main = result.Get<Model.SK_SalebillVouch>("main");
            return true;
        }


        public static bool VouchToFP_RD_Proc_Status(int id,bool bShowErr)
        {
            var err = "";
            var url = string.Format("{0}/api/oms/Rd2SK/GetFPStatusRd?token={1}&id={2}",
            ServerConfig.ServerAddress, ServerConfig.GetToken(), id);
            var resultval = Common.handleHttp.Get(url);
            var result = Common.handleJSON.DeserializeResult(resultval);
            if (result.result != 1)
            {
                err = result.resultdetail;
                err = System.Web.HttpUtility.UrlDecode(err);
                if(!err.StartsWith("CLOSED"))
                {
                    if (!bShowErr)
                    {
                        err = "开票申请已经发送成功，正在排队开票中，请稍后再查询状态";
                        var fsuc = new FrmMessage();
                        fsuc.ShowMsg(true, "电子发票查询状态", err);
                        return true;
                    }
                }
                var ferr = new FrmMessage();
                ferr.ShowMsg(false, "电子发票查询状态有错，请下次再查询", err);
                return false;
            }
            else
            {
                err = result.resultdetail;
                var fsuc = new FrmMessage();
                fsuc.ShowMsg(true, "电子发票开具成功", err);
                return true;
            }
        }
        #endregion


        #region 修改-开票申请
        /// <summary>
        /// 修改-开票申请
        /// </summary>
        public void Modify_RD()
        {
            try
            {
                var url = string.Format("{0}/api/oms/Rdrecord11/Modify?token={1}&id={2}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken(), this._id);
                var d = new Dictionary<string, object>();
                d.Add("ID", this._id); d.Add("ts", this._ts);
                var s = Common.handleHttp.Post(d, url);
                var result = Common.handleJSON.DeserializeResult(s);
                if (result.result != 1)
                {
                    MessageBox.Show("出错:" + result.resultdetail); return;
                }

                #region 显示数据
                var rd = (Dictionary<string, object>)result.GetVal("rdrecord");
                this._id = rd["ID"].ObjToInt();
                this._ts = rd["ts"].ObjToString();
                var rds = result.GetListDic("rdrecords");
                this.DisplayDataForm(rd);
                this.Displaydata(rds, true);
                this.SetToolBarEnable(false);
                this._bVouchModifyStatus = true;
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion

        #region 保存-开票申请
        /// <summary>
        /// 保存-开票申请
        /// </summary>
        public void SaveVouch_RD()
        {
            try
            {
                string err;
                List<Dictionary<string, object>> list;
                var dic_main = this.GetVouchData(out err, out list);
                if (err.Length > 0)
                {
                    MessageBox.Show("获取单据数据出现错误：" + err); return;
                }

                string url;
                if (this._id == 0)
                {
                    url = string.Format("{0}/api/oms/Rdrecord11/AddTry?token={1}",
                          ServerConfig.ServerAddress, ServerConfig.GetToken());
                }
                else
                {
                    url = url = string.Format("{0}/api/oms/Rdrecord11/UpdateTry?token={1}",
                          ServerConfig.ServerAddress, ServerConfig.GetToken());
                }

                dic_main.Add("detail", list);
                var poststr = Common.handleJSON.Serialize(dic_main);
                var s = Common.handleHttp.Post(poststr, url);
                var result = Common.handleJSON.DeserializeResult(s);
                if (result.result == 1001)
                {
                    var dr = MessageBox.Show(result.resultdetail, "警告", MessageBoxButtons.YesNo);
                    if (dr == DialogResult.No)
                    { return; }
                }
                else
                {
                    if (result.result != 1) { MessageBox.Show(result.resultdetail); }
                }
                if (this._id == 0)
                {
                    url = string.Format("{0}/api/oms/Rdrecord11/Add?token={1}",
                          ServerConfig.ServerAddress, ServerConfig.GetToken());
                }
                else
                {
                    url = string.Format("{0}/api/oms/Rdrecord11/Update?token={1}",
                          ServerConfig.ServerAddress, ServerConfig.GetToken());
                }
                s = Common.handleHttp.Post(poststr, url);
                result = Common.handleJSON.DeserializeResult(s);
                if (result.result != 1) { MessageBox.Show("保存出错:" + result.resultdetail); return; }

                #region 显示数据
                var rd = (Dictionary<string, object>)result.GetVal("rdrecord");
                this._id = rd["ID"].ObjToInt();
                this._ts = rd["ts"].ObjToString();
                var rds = result.GetListDic("rdrecords");
                this.DisplayDataForm(rd);
                this.Displaydata(rds, true);
                this.SetToolBarEnable(true);
                this._bVouchModifyStatus = false;
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show("服务器系统返回错误:" + ex.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace);
            }

        }
        #endregion



        #region 审核按钮-开票申请
        /// <summary>
        /// 审核按钮-开票申请
        /// </summary>
        public void Verify_Rd()
        {
            try
            {
                var url = string.Format("{0}/api/oms/Rdrecord11/VerifyTry?token={1}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken());
                var pos = new Dictionary<string, object>();
                pos.Add("ID", this._id);
                pos.Add("ts", this._ts);
                var s = Common.handleHttp.Post(pos, url);
                var result = Common.handleJSON.DeserializeResult(s);
                if (result.result == -1 || result.result == 1002)
                {
                    MessageBox.Show(result.resultdetail); return;
                }
                if (result.result == 1001)
                {
                    var dr = MessageBox.Show(result.resultdetail, "提示", MessageBoxButtons.YesNo);
                    if (dr == DialogResult.No)
                    { return; }
                }

                url = string.Format("{0}/api/oms/Rdrecord11/Verify?token={1}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken());
                s = Common.handleHttp.Post(pos, url);
                result = Common.handleJSON.DeserializeResult(s);

                if (result.result != 1) { MessageBox.Show("审核出错:" + result.resultdetail); return; }
                MessageBox.Show("审核成功!");
                #region 显示数据
                var customer = (Dictionary<string, object>)result.GetVal("Customer");
                var rd = (Dictionary<string, object>)result.GetVal("rdrecord");
                this._id = rd["ID"].ObjToInt();
                this._ts = rd["ts"].ObjToString();
                var rds = result.GetListDic("rdrecords");
                this.DisplayDataForm(customer, rd);
                this.Displaydata(rds, true);
                this.SetToolBarEnable(true);
                this._bVouchModifyStatus = false;
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion

        #region 弃审核-开票申请
        /// <summary>
        /// 弃审核-开票申请
        /// </summary>
        public void UnVerify_Rd()
        {
            try
            {
                var url = string.Format("{0}/api/oms/Rdrecord11/UnVerifyTry?token={1}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken());
                var pos = new Dictionary<string, object>();
                pos.Add("ID", this._id);
                pos.Add("ts", this._ts);
                var s = Common.handleHttp.Post(pos, url);
                var result = Common.handleJSON.DeserializeResult(s);
                if (result.result == -1 || result.result == 1002)
                {
                    MessageBox.Show(result.resultdetail); return;
                }
                if (result.result == 1001)
                {
                    var dr = MessageBox.Show(result.resultdetail, "提示", MessageBoxButtons.YesNo);
                    if (dr == DialogResult.No)
                    { return; }
                }

                url = string.Format("{0}/api/oms/Rdrecord11/UnVerify?token={1}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken());
                s = Common.handleHttp.Post(pos, url);
                result = Common.handleJSON.DeserializeResult(s);

                if (result.result != 1) { MessageBox.Show("弃审出错:" + result.resultdetail); return; }
                MessageBox.Show("弃审成功!");
                #region 显示数据
                var customer = (Dictionary<string, object>)result.GetVal("Customer");
                var rd = (Dictionary<string, object>)result.GetVal("rdrecord");
                this._id = rd["ID"].ObjToInt();
                this._ts = rd["ts"].ObjToString();
                var rds = result.GetListDic("rdrecords");
                this.DisplayDataForm(customer, rd);
                this.Displaydata(rds, true);
                this.SetToolBarEnable(true);
                this._bVouchModifyStatus = false;
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion


        #region 重新传输税控-税控发票
        /// <summary>
        /// 重新传输税控-税控发票
        /// </summary>
        public void VouchToFPRe_SK(Form parent)
        {
            try
            {
                var url = string.Format("{0}/api/oms/SKSalebillVouch/GetOne?token={1}&ID={2}",
                    ServerConfig.ServerAddress, ServerConfig.GetToken(), this._id);
                var val = Common.handleHttp.Get(url);
                var result = Common.handleJSON.DeserializeResult(val);
                if (result.result != 1) { MessageBox.Show("出错:" + result.resultdetail); return; }

                var sk = result.Get<Model.SK_SalebillVouch>("main");
                this._id = sk.ID;
                var l_sks = result.GetList<Model.SK_SalebillVouchs_View>("details");
                string err="";
                err = cSK.SoftSel.proc(sk, l_sks);
                if (err.Length > 0) { MessageBox.Show(err); }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
            finally { parent.Show(); }
        }
        #endregion


        #region 获取电子发票状态-开票申请
        /// <summary>
        /// 获取电子发票状态-开票申请
        /// </summary>
        public void VouchStatus_Rd()
        {
            VouchToFP_RD_Proc_Status(this._id,true);
            //var url = string.Format("{0}/api/oms/Rd2SK/GetFPStatusRd?token={1}&id={2}",
            // ServerConfig.ServerAddress, ServerConfig.Token, this._id);
            //var s = Common.handleHttp.Get(url);
            //var result = Common.handleJSON.DeserializeResult(s);
            //if (result.result == 1) { MessageBox.Show(result.resultdetail); }
            //else
            //{
            //    var frm = new FrmMessage();
            //    frm.ShowMsg(false, "查询状态不成功，请提供一下信息给技术员", result.resultdetail);
            //}
        }
        #endregion


        #region 获取电子发票状态-税控发票
        /// <summary>
        /// 获取电子发票状态-税控发票
        /// </summary>
        public void VouchStatus_SK()
        {
            string err;
            var bret = VouchStatus_SK_Proc(this._id, out err);
            var frm = new FrmMessage();
            frm.ShowMsg(bret,"提醒",err );
        }
        /// <summary>
        /// 获取电子发票状态-税控发票
        /// </summary>
        public static bool VouchStatus_SK_Proc(int id,out string err)
        {
            var url = string.Format("{0}/api/oms/Rd2SK/GetFPStatusSK?token={1}&id={2}",
             ServerConfig.ServerAddress, ServerConfig.GetToken(), id);
            var s = Common.handleHttp.Get(url);
            var result = Common.handleJSON.DeserializeResult(s);
            if (result.result == 1) { err=result.resultdetail; return true; }
            else
            {
                var resultmsg = System.Web.HttpUtility.UrlDecode(result.resultdetail);
                err = string.Format("查询状态不成功，请提供一下信息给技术员：{0}", resultmsg);
                return false;
            }
        }
        #endregion


        #region 获取电子发票的PDF文件
        /// <summary>
        /// 获取电子发票的PDF文件
        /// </summary>
        public void DownloadPDF_SK(int id)
        {
            var url = string.Format("{0}/api/oms/Rd2SK/DownloadPDF_SK?token={1}&id={2}",
              ServerConfig.ServerAddress, ServerConfig.GetToken(), id);
            var filename = Common.handleHttp.DownLoadFile(url);
            if (filename.Length > 0)
            {
                var msg = string.Format("电子发票文件下载成功，放在{0}，需要打开么？", filename);
                var dr = MessageBox.Show(msg, "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (dr == DialogResult.No) { return; }
                System.Diagnostics.Process.Start(filename);
            }
        }
        #endregion

        #region 获取电子发票的PDF文件
        /// <summary>
        /// 获取电子发票的PDF文件
        /// </summary>
        public void DownloadPDF_RD(int id)
        {
            var url = string.Format("{0}/api/oms/Rd2SK/DownloadPDF_RD?token={1}&id={2}",
              ServerConfig.ServerAddress, ServerConfig.GetToken(), id);
            var filename = Common.handleHttp.DownLoadFile(url);
            if (filename.Length > 0)
            {
                var msg = string.Format("电子发票文件下载成功，放在{0}，需要打开么？", filename);
                var dr = MessageBox.Show(msg, "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (dr == DialogResult.No) { return; }
                System.Diagnostics.Process.Start(filename);
            }
        }
        #endregion

        #region 拆单开票
        /// <summary>
        /// 拆单开票
        /// </summary>
        public static void CDKP(int id)
        {
            try
            {
                var f = new FrmKP.FrmCD();
                f.Show();
                f.Reflesh(id);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion


        #region 金立分销--上海
        /// <summary>
        /// 金立分销
        /// </summary>
        /// <param name="oldURL"></param>
        //public void DownLoadFromERPSH(string oldURL, string stype)
        //{
        //    try
        //    {
        //        _id = 0; _ts = "";
        //        #region 弹出选择金立分销
        //        var f = new FrmSH.FrmVouchCode();
        //        f.Text = "[" + stype + "]单据引入";
        //        f.ShowDialog(_toolstrip.Parent);
        //        var code = f.cCode;
        //        var idwarehouse = f.idwarehouse;
        //        if (code.ObjToString().Length == 0 || idwarehouse == 0)
        //        { return; }
        //        #endregion

        //        #region 获取销售小票
        //        var url = string.Format(oldURL, ServerConfig.ServerAddress, ServerConfig.Token, code, idwarehouse);
        //        var s = Common.handleHttp.Get(url);
        //        var result = Common.handleJSON.DeserializeResult(s);
        //        if (result.result != 1)
        //        {
        //            var ftip = new FrmSH.FrmYSDZFPFail();
        //            ftip.SetErrMsg("下载单据失败", result.resultdetail);
        //            ftip.ShowDialog();
        //            return;
        //        }
        //        var customer = (Dictionary<string, object>)result.GetVal("Customer");
        //        var rd = (Dictionary<string, object>)result.GetVal("rdrecord");
        //        var rds = result.GetListDic("rdrecords");
        //        #endregion

        //        if (_bVouchModifyStatus == false)
        //        { base.DisplayDataForm(customer, rd); base.Displaydata(rds, true); _id = 0; _ts = ""; base.SetDefaultWarehouse(); }
        //        else { base.Displaydata(rds, false); }
        //        SetToolBarEnable(false);
        //        _bVouchModifyStatus = true;
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message + ex.StackTrace);
        //    }
        //}
        #endregion   

    }
}
